/*
 * ManagerService.java
 *
 * Created on Jun 28, 2007, 7:44:22 PM
 *
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori.events;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author DGronau
 */
public class ManagerService {
    
    private static Map<Class<? extends Event>, Manager> managers = new HashMap<Class<? extends Event>, Manager>();
    
    public static void createManager(Class<? extends Event> clazz) {
        managers.put(clazz, new Manager());
    }
    
    public static void register(Listener<? extends Event> listener) {
        Manager manager = managers.get(listener.getClazz());
        if (manager == null) {
            createManager(listener.getClazz());
            manager = managers.get(listener.getClazz());
        }
        manager.register(listener);
    }
    
    public static void unregister(Listener<? extends Event> listener) {
        Manager manager = managers.get(listener.getClazz());
        if (manager != null) {
            manager.unregister(listener);
        }
    }
    
    public static void unregisterAll(Class<? extends Event> clazz) {
        Manager manager = managers.get(clazz);
        if (manager != null) {
            manager.unregisterAll();
        }
    }
    
    public static  <E extends Event> void fireEvent(E event) {
        Manager manager = managers.get(event.getClass());
        if (manager != null) {
            manager.fireEvent(event);
        }
    }
    
    private static class Manager {
        
        List<Listener<? extends Event>> listeners = new ArrayList<Listener<? extends Event>>();
        
        public void register(Listener<? extends Event> listener) {
            listeners.add(listener);
        }
        
        public void unregister(Listener<? extends Event> listener) {
            listeners.remove(listener);
        }
        
        public void unregisterAll() {
            listeners.clear();
        }
        
        @SuppressWarnings("unchecked")
        public <E extends Event> void fireEvent(E event) {
            for (Listener listener : listeners) {
                ((Listener<E>)listener).notify(event);
            }
        }
        
    }
}
